﻿var insertMode = true;
var AlreadyExistsMessage;
var ExceedesStockMessage;

$(function () {
    
    $.datepicker.setDefaults($.datepicker.regional["es"]);

    $("#_creationDate").datepicker({
        showButtonPanel: true,
        changeMonth: true,
        changeYear: true,
        yearRange: "-100:+10",
        onSelect: function (dateText, inst) {
            var date = $(this).datepicker('getDate'),
            day = date.getDate(),
            month = date.getMonth() + 1,
            year = date.getFullYear();
            $("#CreationDate").val(month + "-" + day + "-" + year)
        }
    });

    $("#Save").click(function () {
        $("#InvoiceContent").mask("Cargando...");

        //START DELIVERY NOTES
        var index = 0;
        var rowIndex = 0;
        $("tr[id^='rowDeliveryNote_']").each(function () {
            rowIndex = $(this).attr("id").substr($(this).attr("id").indexOf("_") + 1);
            $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceDeliveryNotes_" + index + "DeliveryNoteID")
                             .attr("name", "InvoiceDeliveryNotes[" + index + "].DeliveryNoteID")
                             .val($("#DeliveryNote_DeliveryNoteID_" + rowIndex).val())
                             .appendTo("#DeliveryNoteTable");
            index++;
        });
        //END DELIVERY NOTES

        //START REPLACEMENTS
        var index = 0;
        $("tr[id^='rowReplacement_']").each(function () {
            rowIndex = $(this).attr("id").substr($(this).attr("id").indexOf("_") + 1);
            if ($("#Replacement_Quantity_" + rowIndex).val() > 0) {
                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceReplacements_" + index + "ReplacementID")
                             .attr("name", "InvoiceReplacements[" + index + "].ReplacementID")
                             .val($("#Replacement_ReplacementID_" + rowIndex).val())
                             .appendTo("#ReplacementTable");

                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceReplacements_" + index + "Quantity")
                             .attr("name", "InvoiceReplacements[" + index + "].Quantity")
                             .val($("#Replacement_Quantity_" + rowIndex).val())
                             .appendTo("#ReplacementTable");

                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceReplacements_" + index + "UnitPrice")
                             .attr("name", "InvoiceReplacements[" + index + "].UnitPrice")
                             .val($("#Replacement_UnitPrice_" + rowIndex).val())
                             .appendTo("#ReplacementTable");

                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceReplacements_" + index + "TotalPrice")
                             .attr("name", "InvoiceReplacements[" + index + "].TotalPrice")
                             .val($("#Replacement_TotalPrice_" + rowIndex).val())
                             .appendTo("#ReplacementTable");
                index++;
            }
        });
        //END REPLACEMENTS

        //START EXTRA ITEMS
        index = 0;
        $("tr[id^='rowExtraItem_']").each(function () {
            rowIndex = $(this).attr("id").substr($(this).attr("id").indexOf("_") + 1);
            if ($("#ExtraItem_Quantity_" + rowIndex).val() > 0) {
                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceExtraItems_" + index + "Description")
                             .attr("name", "InvoiceExtraItems[" + index + "].Description")
                             .val($("#ExtraItem_Description_" + rowIndex).val())
                             .appendTo("#ExtraItemTable");

                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceExtraItems_" + index + "Quantity")
                             .attr("name", "InvoiceExtraItems[" + index + "].Quantity")
                             .val($("#ExtraItem_Quantity_" + rowIndex).val())
                             .appendTo("#ExtraItemTable");

                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceExtraItems_" + index + "UnitPrice")
                             .attr("name", "InvoiceExtraItems[" + index + "].UnitPrice")
                             .val($("#ExtraItem_UnitPrice_" + rowIndex).val())
                             .appendTo("#ExtraItemTable");

                $("<input/>").attr("type", "hidden")
                             .attr("id", "InvoiceExtraItems_" + index + "TotalPrice")
                             .attr("name", "InvoiceExtraItems[" + index + "].TotalPrice")
                             .val($("#ExtraItem_TotalPrice_" + rowIndex).val())
                             .appendTo("#ExtraItemTable");
                index++;
            }
        });
        //END EXTRA ITEMS
    });

    $("#Cancel").click(function () {
        window.location.href = $Url.resolve("~/Invoice/Index");
    });

    $("#CompanyName").autocomplete({
        minLength: 1,
        delay: 0,
        source: function (request, response) {
            $.ajax({
                url: $Url.resolve("~/Customer/GetCustomersByBusinessUnitID"),
                dataType: "json",
                data: { sortColumn: 'CompanyName', companyName: $("#CompanyName").val() },
                success: function (customers) {
                    response($.map(customers, function (customer) {
                        return { label: customer.CompanyName, value: customer.CustomerID }
                    }));
                }
            });
        },
        select: function (event, ui) {
            $("#CompanyName").val(ui.item.label);
            $("#CustomerID").val(ui.item.value);
            LoadCustomerDeliveryNotes();
            return false;
        },
        change: function (event, ui) {
            if (ui.item == null) {
                $("#CompanyName").val("");
                $("#CustomerID").val("");
            }
            $("[id*='rowDeliveryNote_']").each(function () {
                $(this).remove();
            });
            CalculateSubTotalPrice("DeliveryNote");
            return false;
        }
    });

    $("#ReplacementName").autocomplete({
        minLength: 1,
        delay: 0,
        source: function (request, response) {
            $.ajax({
                url: $Url.resolve("~/Replacement/GetReplacementsByBusinessUnitIDByFilter"),
                dataType: "json",
                data: { filter: $("#ReplacementName").val() },
                success: function (replacements) {
                    response($.map(replacements, function (replacement) {
                        return { label: replacement.Name, value: replacement.ReplacementID }
                    }));
                }
            });
        },
        select: function (event, ui) {
            $("#ReplacementName").val(ui.item.label);
            $("#ReplacementID").val(ui.item.value);
            return false;
        },
        change: function (event, ui) {
            if (ui.item == null) {
                $("#ReplacementName").val("");
                $("#ReplacementID").val("");
            }
            return false;
        }
    });

    $("#AddReplacement").live("click", function () {
        if ($("#ReplacementID").val() != "") {
            var exists = false;
            $("[id*='Replacement_ReplacementID_']").each(function () {
                if ($(this).val() == $("#ReplacementID").val()) {
                    exists = true
                }
            });
            if (!exists) {
                $.ajax({
                    url: $Url.resolve("~/Replacement/GetReplacementByID"),
                    dataType: "json",
                    data: { id: $("#ReplacementID").val() },
                    success: function (replacement) {


                        $("#ReplacementTable").append("<tr id='rowReplacement_" + rowReplacementIndex + "' class='detail'>" +
                                                   "<td>" +
                                                       "<input type='hidden' value='" + replacement.ReplacementID + "' id='Replacement_ReplacementID_" + rowReplacementIndex + "' />" +
                                                       "<input type='hidden' value='" + replacement.Stock + "' id='Replacement_Stock_" + rowReplacementIndex + "' />" +
                                                       "<img src='../../Content/Images/cross.png' onclick='DeleteRow(" + rowReplacementIndex + ", \"Replacement\")'/>" +
                                                   "</td>" +
                                                   "<td>" +
                                                       "<input type='text' value='0' id='Replacement_Quantity_" + rowReplacementIndex + "' onchange='ModifyPrice(" + rowReplacementIndex + ", \"Replacement\")' />" +
                                                   "</td>" +
                                                   "<td>" +
                                                       replacement.Name +
                                                   "</td>" +
                                                   "<td>" +
                                                       "<input type='text' value='" + replacement.PublicPrice + "' id='Replacement_UnitPrice_" + rowReplacementIndex + "' onchange='UnitPrice_Change(this, " + rowReplacementIndex + ", \"Replacement\" )' />" +
                                                   "</td>" +
                                                   "<td>" +
                                                       "<input readonly='readonly' type='text' value='0' id='Replacement_TotalPrice_" + rowReplacementIndex + "' />" +
                                                    "</td>" +
                                                "</tr>");
                        rowReplacementIndex++;

                    }
                });
            } else {
                alert(AlreadyExistsMessage);
            }
        }
    });

    $("#AddExtraItem").live("click", function () {
        if ($("#ExtraItemName").val() != "") {
            $("#ExtraItemTable").append("<tr id='rowExtraItem_" + rowExtraItemIndex + "' class='detail'>" +
                                                   "<td>" +
                                                       "<img src='../../Content/Images/cross.png' onclick='DeleteRow(" + rowExtraItemIndex + ", \"ExtraItem\")'/>" +
                                                   "</td>" +
                                                   "<td>" +
                                                       "<input type='text' value='0' id='ExtraItem_Quantity_" + rowExtraItemIndex + "' onchange='ModifyPrice(" + rowExtraItemIndex + ", \"ExtraItem\")' />" +
                                                   "</td>" +
                                                   "<td>" +
                                                        "<input readonly='readonly' type='text' value='" + $("#ExtraItemName").val() + "' id='ExtraItem_Description_" + rowExtraItemIndex + "' />" +
                                                   "</td>" +
                                                   "<td>" +
                                                       "<input type='text' value='0' id='ExtraItem_UnitPrice_" + rowExtraItemIndex + "' onchange='UnitPrice_Change(this, " + rowExtraItemIndex + ", \"ExtraItem\" )' />" +
                                                   "</td>" +
                                                   "<td>" +
                                                       "<input readonly='readonly' type='text' value='0' id='ExtraItem_TotalPrice_" + rowExtraItemIndex + "' />" +
                                                    "</td>" +
                                                "</tr>");
            rowExtraItemIndex++;
        }
    });

    $("#AddDeliveryNote").live("click", function () {
        if ($("#DeliveryNoteList").val() != 0) {
            var exists = false;
            $("[id*='DeliveryNote_DeliveryNoteID_']").each(function () {
                if ($(this).val() == $("#DeliveryNoteList").val()) {
                    exists = true
                }
            });
            if (!exists) {
                $.ajax({
                    url: $Url.resolve("~/DeliveryNote/GetDeliveryNoteByID"),
                    dataType: "json",
                    data: { deliveryNoteID: $("#DeliveryNoteList").val() },
                    success: function (deliveryNote) {

                        $("#DeliveryNoteTable").append("<tr id='rowDeliveryNote_" + rowDeliveryNoteIndex + "' class='detail'>" +
                                                        "<td>" +
                                                            "<img src='../../Content/Images/cross.png' onclick='DeleteRow2(" + rowDeliveryNoteIndex + ", \"DeliveryNote\"," + deliveryNote.DeliveryNoteID + " )'/>" +
                                                        "</td>" +
                                                        "<td>" +
                                                            "<input readonly='readonly' type='text' value='" + deliveryNote.DeliveryNoteID + "' id='DeliveryNote_DeliveryNoteID_" + rowDeliveryNoteIndex + "' />" +
                                                        "</td>" +
                                                        "<td>" +
                                                            "<input readonly='readonly' type='text' value='" + deliveryNote.DeliveryNoteTotalPrice + "' id='DeliveryNote_TotalPrice_" + rowDeliveryNoteIndex + "' />" +
                                                        "</td>" +
                                                    "</tr>");
                        rowDeliveryNoteIndex++;
                        $("#DeliveryNoteList option[value='" + deliveryNote.DeliveryNoteID + "']").remove();
                        CalculateSubTotalPrice("DeliveryNote");
                    }
                    //                    ,error: function (request, error) {
                    //                        console.log(arguments);
                    //                        alert(" Can't do because: " + error);
                    //                    }
                });
            } else {
                alert(AlreadyExistsMessage);
            }
        }
    });

    Custom.init();

});

function DeleteRow(rowIndex, rowName) {
    $("#row" + rowName + "_" + rowIndex).remove();
    CalculateSubTotalPrice(rowName);
}

function DeleteRow2(rowIndex, rowName, ID) {
    $("#row" + rowName + "_" + rowIndex).remove();
    $('#DeliveryNoteList').append($('<option>', { value: ID, text: ID }));
    CalculateSubTotalPrice(rowName);
}

function ModifyPrice(rowIndex, rowName) {
    if (CheckStock(rowIndex, rowName)) {
        var quantity = $("#" + rowName + "_Quantity_" + rowIndex).val();
        var unitPrice = $("#" + rowName + "_UnitPrice_" + rowIndex).val();
        var totalPrice = Math.round((unitPrice * quantity * 100)) / 100;
        $("#" + rowName + "_TotalPrice_" + rowIndex).val(totalPrice);
        CalculateSubTotalPrice(rowName);
    } else {
        alert(ExceedesStockMessage);
        $("#" + rowName + "_Quantity_" + rowIndex).val("0");
        $("#" + rowName + "_Quantity_" + rowIndex).change();
    }
}

function CheckStock(rowIndex, rowName) {
    if (parseInt($("#" + rowName + "_Quantity_" + rowIndex).val()) > parseInt($("#" + rowName + "_Stock_" + rowIndex).val()))
        return false;
    else
        return true;
}


function UnitPrice_Change(obj, rowIndex, rowName) {
    if (obj.value.indexOf(",") > -1) {
        obj.value = obj.value.replace(",", ".");
        $(obj).trigger('change');
        return false;
    }
    try {
        var newValue = Math.round((obj.value * 100)) / 100;
        if (obj.value != newValue) {
            obj.value = newValue;
            $(obj).trigger('change');
            return false;
        }

    }
    catch (err) {
        obj.value = "";
    }
    ModifyPrice(rowIndex, rowName);
}

function CalculateSubTotalPrice(rowName) {
    var subTotalPrice = 0;
    $("[id*='" + rowName + "_TotalPrice_']").each(function () {
        subTotalPrice += parseFloat($(this).val());
    });
    subTotalPrice = Math.round((subTotalPrice * 100)) / 100
    $("#Invoice_" + rowName + "s_Total_Price").text(subTotalPrice);
    CalculateTotalPrice();

}

function CalculateTotalPrice() {
    var totalPrice = 0;
    totalPrice = parseFloat($("#Invoice_Replacements_Total_Price").text()) + parseFloat($("#Invoice_ExtraItems_Total_Price").text()) + parseFloat($("#Invoice_DeliveryNotes_Total_Price").text());
    totalPrice = Math.round((totalPrice * 100)) / 100
    $("#Invoice_Total_Price").text(totalPrice)
}

function LoadCustomerDeliveryNotes() {
    $.ajax({
        url: $Url.resolve("~/DeliveryNote/GetAvailableDeliveryNotesByCustomerID"),
        dataType: "json",
        data: { customerID: $("#CustomerID").val() },
        success: function (deliveryNotes) {
            $("#DeliveryNoteList").empty();
            $('#DeliveryNoteList').append($('<option>', { value: '0', text: 'Seleccionar...' }));
            $.each(deliveryNotes, function (key, value) {
                $('#DeliveryNoteList').append($('<option>', { value: value.DeliveryNoteID, text: value.DeliveryNoteID }));
            });
        }
    });
}

function submitCompleted(content) {
    $("#InvoiceContent").unmask();
    window.location.href = $Url.resolve("~/Invoice/Index");
}